const app = getApp()
import Toast from '@vant/weapp/toast/toast';
import {
    reqLogin,
    reqUserInfo,
    reqWxLogin,
    reqOrgList,
    reqUpdateUser,
    reqSmsCode,
    reqSmsLogin
} from '../../request/api.js'
import {
    validateUsername,
    checkRegNo,
    validateMobile
} from '../../utils/validate.js'
Page({
    data: {
        srcUsername: '../../statics/images/login-register/username_icon.png',
        srcPwd: '../../statics/images/login-register/pwd_icon.png',
        srcEyeClose: '../../statics/images/login-register/eye_close_icon.png',
        srcEyeOpen: '../../statics/images/login-register/eye_open_icon.png',
        username: '',
        password: '',
        isPassword: true,
        version: app.globalData.version,
        checkedDeal: true,
        informationShow: false, //首次登录完善个人信息
        username2: "",
        idCard: "",
        mode: "account",// phone
        srcMobile: '../../statics/images/login-register/mobile_icon.png',
        srcMessage: '../../statics/images/login-register/message_icon.png',
        showCountDown: false, //是否展示倒计时
        countDown: '', //60s倒计时
        code: '',
        mobile: '',
    },

    onLoad: function (options) {
        console.log(app.globalData.unitLevelList, "app.globalData.unitLevelList")
    },
    onmode() {
        this.setData({
            mode: 'phone'
        })
    },
    onphone() {
        console.log(111)
        this.setData({
            mode: 'account'
        })
    },
    // 获取用户名
    usernameChange(e) {
        this.setData({
            username: e.detail.value
        })
    },
    // 清除用户名
    clearUsername() {
        this.setData({
            username: ''
        })
    },
    // 获取密码
    passwordChange(e) {
        this.setData({
            password: e.detail.value
        })
    },
    // 清除密码
    clearPassword() {
        this.setData({
            password: ''
        })
    },
    //  密码显隐
    showPassword() {
        this.setData({
            isPassword: !this.data.isPassword
        })
    },
    goLogin() {
        let {
            username,
            password,
            mode,
            mobile,
            code
        } = this.data
        if (mode == 'phone') {
            if (!mobile) return Toast("请输入手机号")
            if (!code) return Toast("请输入验证码")
        } else {
            if (!username) return Toast("请输入用户名或手机号")
            if (!password) return Toast("请输入密码")
        }
        let that = this
        wx.login({
            async success(res) {
                if (res.code) {
                    let res1;
                    if (mode == 'phone') {
                        res1 = await reqSmsLogin({
                            mobile,
                            code
                        })
                    } else {
                        res1 = await reqLogin({
                            username,
                            password
                        })
                    }
                    if (res1.code == 11133) return Toast.fail({
                        message: '账号未设置登陆密码，请使用短信登录',
                    });
                    if (res1.code != 20000) return Toast.fail({
                        message: res1.message,
                    });
                    let {
                        id: userId,
                        token
                    } = res1.data.row
                    app.globalData.userId = userId
                    wx.setStorageSync('userId', userId);
                    app.globalData.token = token
                    wx.setStorageSync('token', token);
                    that.getUserInfo(userId) //获取用户信息
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })

    },
    // 微信登录
    wxLogin() {
        let that = this
        wx.login({
            async success(res) {
                console.log(res);
                if (res.code) {
                    const res1 = await reqWxLogin({
                        jsCode: res.code
                    })
                    if (res1.code === 10063) return Toast('微信未绑定，请登录后进行绑定')
                    if (res1.code !== 20000) return Toast(res1.data.message)
                    let {
                        row
                    } = res1.data
                    app.globalData.token = row.token
                    wx.setStorageSync('token', row.token)
                    app.globalData.userId = row.id
                    wx.setStorageSync('userId', row.id)
                    that.getUserInfo(row.id)
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })
    },
    // 获取个人信息
    async getUserInfo(id) {
        const res = await reqUserInfo(id)
        if (res.code != 20000) return
        let {
            mobile,
            nickname,
            tenantId,
            username,
            idCard,
            openId,
            wxNickName,
            avatar
        } = res.data.row

        let {
            name: rolename,
            description: descriptionRole
        } = res.data.row.role

        app.globalData.avatar = avatar; //存储头像
        wx.setStorageSync('avatar', avatar); //存储头像
        app.globalData.mobile = mobile
        wx.setStorageSync('mobile', mobile);
        app.globalData.nickname = nickname
        wx.setStorageSync('nickname', nickname);
        app.globalData.tenantId = tenantId
        wx.setStorageSync('tenantId', tenantId);
        app.globalData.username = username
        wx.setStorageSync('username', username);
        app.globalData.idCard = idCard
        wx.setStorageSync('idCard', idCard);

        app.globalData.openId = openId
        wx.setStorageSync('openId', openId);
        app.globalData.wxNickName = wxNickName
        wx.setStorageSync('wxNickName', wxNickName);

        app.globalData.rolename = rolename
        wx.setStorageSync('rolename', rolename);
        app.globalData.descriptionRole = descriptionRole
        wx.setStorageSync('descriptionRole', descriptionRole);

        if (username == '') {
            app.globalData.isProprietor = true
            wx.setStorageSync('isProprietor', true);
            // 业主没用户名情况,去完善用户名
            wx.redirectTo({
                url: '/packageA/pages/index-inside-page/information-list/information-list',
            })
            // this.setData({
            //     'informationShow': true,
            //     username2: "",
            //     idCard:""
            // })
            return;
        }

        if (rolename == 'NORMAL_USER') {
            // 业主不需要选择单位
            app.globalData.isProprietor = true
            wx.setStorageSync('isProprietor', true);
            wx.switchTab({
                url: '/pages/index/index',
            })
            return;
        }
        app.globalData.isProprietor = false
        wx.setStorageSync('isProprietor', false);

        wx.switchTab({
            url: '/pages/index/index',
        })

        // this.getOrgList()
    },

    async getOrgList() {
        let params = {
            tenantId: app.globalData.tenantId,
            userId: app.globalData.userId,
            roleName: app.globalData.rolename,
            type: "1,2,3,4"
        }
        const res = await reqOrgList(1, 10, params)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        if (rows.length <= 0) {
            // 1、如果没有组织，则去创建或者加入
            wx.redirectTo({
                url: '/pages/personal-inside-page/org-addOrCreate/org-addOrCreate',
            })
        } else if (rows.length === 1) {
            console.log(rows, 'rows');
            //2、否则如果有一个组织，则直接去首页
            app.globalData.orgId = rows[0].id
            wx.setStorageSync('orgId', rows[0].id);
            app.globalData.orgId2 = rows[0].tenantId
            wx.setStorageSync('orgId2', rows[0].tenantId);
            app.globalData.orgName = rows[0].orgName
            wx.setStorageSync('orgName', rows[0].orgName);
            app.globalData.isTeamManager = rows[0].role === 1 ? true : false //role为1：单位管理员 role为2：消防安全员
            wx.setStorageSync('isTeamManager', rows[0].role === 1 ? true : false);
            wx.switchTab({
                url: '/pages/index/index',
            })
        } else {
            // 3、否则存在多个组织，去组织列表选择一个
            wx.redirectTo({
                url: '/pages/personal-inside-page/org/org',
            })
        }
    },
    // 确定
    async bindtapShoudon() {
        if (!validateUsername(this.data.username2)) return
        if (!checkRegNo(this.data.idCard)) return
        const res = await reqUpdateUser({
            id: app.globalData.userId,
            nickname: app.globalData.nickname,
            username: this.data.username2,
            idCard: this.data.idCard
        })
        if (res.code != 20000) return Toast.fail(res.message);
        // Toast.success("修改成功")
        app.globalData.username = this.data.username2
        wx.setStorageSync('username', this.data.username2);
        if (app.globalData.rolename == 'NORMAL_USER') {
            // 业主不需要选择单位
            app.globalData.isProprietor = true
            wx.setStorageSync('isProprietor', true);
            wx.switchTab({
                url: '/pages/index/index',
            })
            return;
        }
        app.globalData.isProprietor = false
        wx.setStorageSync('isProprietor', false);
        this.getOrgList()
    },

    goRegister() {
        wx.navigateTo({
            url: '/pages/register/register',
        })
    },
    goForgetPwd() {
        wx.navigateTo({
            url: '/pages/forget-pwd/forget-pwd',
        })
    },
    onClose() {
        this.setData({
            'informationShow': false,
        })
    },
    handleusername(e) {
        this.setData({
            'username2': e.detail.value
        })
    },
    username2Clear(event) {
        this.setData({
            username2: "",
        })
    },
    handleidCard(e) {
        this.setData({
            'idCard': e.detail.value
        })
    },
    idCardClear() {
        this.setData({
            idCard: "",
        })
    },
    // 获取手机号
    mobileChange(e) {
        this.setData({
            mobile: e.detail.value
        })
    },
    // 清除短信验证码
    clearSmsCode() {
        this.setData({
            code: ''
        })
    },
    async getSmsCodeClick() {
        if (this.data.showCountDown) return
        let {
            mobile
        } = this.data
        if (!validateMobile(mobile)) return
        const res = await reqSmsCode({
            mobile
        })
        if (res.code != 20000) return Toast(res.data.errorInfo);
        Toast("请注意查收手机短信验证码")
        this.setData({
            showCountDown: true,
            countDown: 60,
            smsCodeMobile: mobile
        })
        let intervalId = setInterval(() => {
            let {
                countDown
            } = this.data
            if (this.data.countDown > 0 && this.data.countDown <= 60) {
                countDown -= 1
                this.setData({
                    countDown
                })
            } else {
                this.setData({
                    showCountDown: false
                })
                clearInterval(intervalId);
                intervalId = null;
            }
        }, 1000);
    },
    // 清除手机号
    clearMobile() {
        this.setData({
            mobile: ''
        })
    },
    // 获取短信
    smsCodeChange(e) {
        this.setData({
            code: e.detail.value
        })
    },
})